import React, { useState, useEffect } from 'react'
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons'

export type ToastType = 'success' | 'error' | 'warning' | 'info'

interface ToastProps {
  message: string
  type: ToastType
  duration?: number
  onClose: () => void
}

const Toast: React.FC<ToastProps> = ({
  message,
  type,
  duration = 3000,
  onClose,
}) => {
  const [isVisible, setIsVisible] = useState(false)

  useEffect(() => {
    // 显示动画
    setTimeout(() => setIsVisible(true), 100)

    // 自动关闭
    const timer = setTimeout(() => {
      setIsVisible(false)
      setTimeout(onClose, 300)
    }, duration)

    return () => clearTimeout(timer)
  }, [duration, onClose])

  const getIcon = () => {
    switch (type) {
      case 'success':
        return <CheckCircleOutlined className="text-green-500" />
      case 'error':
        return <CloseCircleOutlined className="text-red-500" />
      case 'warning':
        return <ExclamationCircleOutlined className="text-yellow-500" />
      case 'info':
        return <InfoCircleOutlined className="text-blue-500" />
      default:
        return <InfoCircleOutlined className="text-blue-500" />
    }
  }

  const getBgColor = () => {
    switch (type) {
      case 'success':
        return 'bg-green-50 border-green-200'
      case 'error':
        return 'bg-red-50 border-red-200'
      case 'warning':
        return 'bg-yellow-50 border-yellow-200'
      case 'info':
        return 'bg-blue-50 border-blue-200'
      default:
        return 'bg-blue-50 border-blue-200'
    }
  }

  return (
    <div
      className={`
        fixed top-4 right-4 z-[9999] max-w-sm
        transform transition-all duration-300 ease-in-out
        ${
          isVisible ? 'translate-x-0 opacity-100' : 'translate-x-full opacity-0'
        }
      `}
    >
      <div
        className={`
          flex items-center p-4 rounded-lg shadow-lg border
          ${getBgColor()}
        `}
      >
        <div className="flex-shrink-0 mr-3">{getIcon()}</div>
        <div className="flex-1">
          <p
            className="text-sm font-medium text-gray-900"
            style={{
              marginTop: '10px',
            }}
          >
            {message}
          </p>
        </div>
        <button
          onClick={() => {
            setIsVisible(false)
            setTimeout(onClose, 300)
          }}
          className="flex-shrink-0 ml-3 text-gray-400 hover:text-gray-600 transition-colors"
        >
          <CloseCircleOutlined />
        </button>
      </div>
    </div>
  )
}

// Toast管理器
interface ToastItem {
  id: string
  message: string
  type: ToastType
  duration?: number
}

class ToastManager {
  private toasts: ToastItem[] = []
  private listeners: Array<(toasts: ToastItem[]) => void> = []

  addToast(message: string, type: ToastType = 'info', duration?: number) {
    const id = Date.now().toString() + Math.random().toString(36).substr(2, 9)
    const toast: ToastItem = { id, message, type, duration }

    this.toasts.push(toast)
    this.notifyListeners()

    // 自动移除
    if (duration !== 0) {
      setTimeout(() => {
        this.removeToast(id)
      }, duration || 3000)
    }
  }

  removeToast(id: string) {
    this.toasts = this.toasts.filter((toast) => toast.id !== id)
    this.notifyListeners()
  }

  subscribe(listener: (toasts: ToastItem[]) => void) {
    this.listeners.push(listener)
    return () => {
      this.listeners = this.listeners.filter((l) => l !== listener)
    }
  }

  private notifyListeners() {
    this.listeners.forEach((listener) => listener([...this.toasts]))
  }

  // 便捷方法
  success(message: string, duration?: number) {
    this.addToast(message, 'success', duration)
  }

  error(message: string, duration?: number) {
    this.addToast(message, 'error', duration)
  }

  warning(message: string, duration?: number) {
    this.addToast(message, 'warning', duration)
  }

  info(message: string, duration?: number) {
    this.addToast(message, 'info', duration)
  }
}

// 全局Toast管理器实例
export const toastManager = new ToastManager()

// Toast容器组件
export const ToastContainer: React.FC = () => {
  const [toasts, setToasts] = useState<ToastItem[]>([])

  useEffect(() => {
    const unsubscribe = toastManager.subscribe(setToasts)
    return unsubscribe
  }, [])

  return (
    <div className="fixed top-0 right-0 z-[9999] p-4 space-y-2">
      {toasts.map((toast) => (
        <Toast
          key={toast.id}
          message={toast.message}
          type={toast.type}
          duration={toast.duration}
          onClose={() => toastManager.removeToast(toast.id)}
        />
      ))}
    </div>
  )
}

export default Toast
